<template>
  <div class="virtual-list" @scroll="handleScroll">
    <!-- 占位元素，撑起整个列表的高度 -->
    <div
      class="virtual-list-placeholder"
      :style="{ height: totalHeight + 'px' }"
    ></div>

    <!-- 可见区域 -->
    <div
      class="virtual-list-content"
      :style="{ transform: `translateY(${offsetY}px)` }"
    >
      <div
        v-for="item in visibleItems"
        :key="item.id"
        class="virtual-list-item"
        :style="{ height: itemHeight + 'px' }"
      >
        {{ item.text }}
      </div>
    </div>
  </div>
</template>

<script>
function throttle(func, delay) {
  let lastTime = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastTime >= delay) {
      func.apply(this, args);
      lastTime = now;
    }
  };
}

export default {
  data() {
    return {
      items: [], // 所有数据
      itemHeight: 50, // 每项的高度
      visibleCount: 0, // 可见区域能显示的数量
      startIndex: 0, // 可见区域的起始索引
      offsetY: 0, // 可见区域的偏移量
    };
  },
  computed: {
    // 计算可见区域的数据
    visibleItems() {
      return this.items.slice(
        this.startIndex,
        this.startIndex + this.visibleCount
      );
    },
    // 计算整个列表的总高度
    totalHeight() {
      return this.items.length * this.itemHeight;
    },
  },
  mounted() {
    // 初始化数据
    this.items = Array.from({ length: 10000 }, (_, i) => ({
      id: i + 1,
      text: `Item ${i + 1}`,
    }));
    // 计算可见区域能显示的数量
    this.visibleCount = Math.ceil(this.$el.clientHeight / this.itemHeight)+2;
    console.log("visibleCount", this.visibleCount);
  },
  methods: {
    
    // 处理滚动事件
    handleScroll: throttle(function (event) {
        console.log(222);
      console.log("event", event);
        const scrollTop = event.target.scrollTop; // 获取滚动距离
        this.startIndex = Math.floor(scrollTop / this.itemHeight); // 计算起始索引
        this.offsetY = this.startIndex * this.itemHeight; // 计算偏移量
    }, 80), // 16ms 节流，约 60 FPS
  },
};
</script>

<style >
.virtual-list {
  height: 500px; /* 容器高度 */
  overflow-y: auto; /* 允许垂直滚动 */
  position: relative;
  border: 1px solid #ccc;
}

.virtual-list-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
}

.virtual-list-content {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
}

.virtual-list-item {
  display: flex;
  align-items: center;
  padding: 10px;
  box-sizing: border-box;
  border-bottom: 1px solid #eee;
}
</style>